<script lang="ts" setup name="protable">
import { reactive, h, ref } from "vue";
import { message, Modal } from "ant-design-vue";
import { setBaseApi, get, post, del } from "@/api/http";
import { isFn } from "@/types/is";
import { useGlobalStore } from "@/stores";
import { watch } from "vue";
const { dictionary, getValByDictionary } = useGlobalStore();

const dictionaryKeys = Object.keys(dictionary);

export interface Column {
  label: string;
  prop: string;
  sorter?: (rowA: any, rowB: any) => number;
  width?: number;
  format?: (val: string | number, row?: any) => string | number;
}

interface Operates {
  编辑?: (row: any) => void;
  详情?: (row: any) => void;
  删除?: string | ((row: any) => void);
}

export interface Props {
  columns: Column[];
  data: any[];
  operate?: Operates;
  // pageSize: number;
  // pageNum: number;
  total?: number;
  selection?: "checkbox" | "radio";
  extraBtns?: number; //额外按钮数
}

const props = defineProps<Props>();

// 分页参数
export interface PageOption {
  // pageNum?:number;
  // pageSize?:number;
  page?: number;
  limit?: number;
}

const emit = defineEmits<{
  afterOperate: [page?: PageOption];
}>();

const operateLabels = Object.keys(props?.operate || {});

const delLoading: boolean = false;

const onDelete = (row: any) => {
  const deleteWay = props?.operate["删除"] as string | Function;

  if (isFn(deleteWay)) {
    deleteWay(row);
  } else {
    const { id } = row;
    // 可以传入删除接口名称 来完成删除逻辑
    del(deleteWay, { id }, "删除", delLoading).then(() => {
      emit("afterOperate");
    });
  }
};
const handleDelete = (row: any) => {
  Modal.warning({
    title: "提示",
    okText: "确认",
    onOk: () => onDelete(row),
    centered: true,
    closable: true,
    content: () =>
      h("div", { class: "m-t-20px text-center" }, [
        h("span", { class: "tracking-1px" }, `确认删除${row.title ?? ""}吗？`),
      ]),
  });
};

const rowClass = (_record: any, index: number) =>
  index % 2 ? "bg-gray-100" : null;

const pageOption = reactive({
  limit: 10,
  page: 1,
});

// 分页器变化回调
const handleTablePageChange = (current: number, pageSize: number) => {
  pageOption.limit = pageSize;
  pageOption.page = current;
  emit("afterOperate");
};
// 分页器配置
const pagination = reactive({
  hideOnSinglePage: true,
  showQuickJumper: true,
  total: props.total,
  showTotal: (total: number) => `共 ${total} 条  `,
  defaultPageSize: 10, //默认10
  pageSizeOptions: [10, 20, 50],
  showSizeChanger: false,
  onShowSizeChange: handleTablePageChange,
  onChange: handleTablePageChange,
});
const updateTotal = (total: number) => (pagination.total = total);

// 行选择器
const selectedRowKeys = ref<string | number[]>([]);
// watch(selectedRowKeys, (v) => console.log(v));

const selectionOption = props.selection
  ? {
      type: props.selection, //选择器类型
      selectedRowKeys,
      onChange: (val: string | number[]) => (selectedRowKeys.value = val),
    }
  : false;

defineExpose({ pageOption, updateTotal, selectedRowKeys });

defineSlots<{
  default?: (props: any) => any;
  operate?: (props: any) => any;
}>();
const screenWidth = document.body.clientWidth;
const size: "small" | "large" = screenWidth < 1600 ? "small" : "large";
// console.log(size);

const formatPosition = ({ securityJob }: any) => {
  const res = dictionary.securityJob.filter(
    ({ value }) => value == securityJob
  );
  if (!res[0]) return "";
  return res[0].label;
};
</script>

<template>
  <a-table
    class="w-full"
    :dataSource="props.data"
    :row-class-name="rowClass"
    :pagination="pagination"
    header-cell-class-name="bg-blue-500"
    rowKey="id"
    :row-selection="selectionOption"
    :bordered="{ cell: false }"
    :size="size"
  >
    <a-table-column
      v-for="(item, i) in props.columns"
      :key="item.prop + i"
      :title="item.label"
      :data-index="item.prop"
      :width="item.width"
      :sorter="item.sorter"
      :ellipsis="true"
      :tooltip="true"
      align="center"
    >
      <template #default="{ record }">
        <!-- 格式化内容 -->
        <template v-if="item.prop == 'securityJob'">
          <a-tooltip :title="formatPosition(record)">
            {{ formatPosition(record) }}
          </a-tooltip>
        </template>
        <template v-else-if="item.prop == 'img'"> </template>
        <template v-else>
          <!-- 在全局字典中包括： -->
          <span v-if="dictionaryKeys.includes(item.prop)">{{
            getValByDictionary(item.prop, record)
          }}</span>

          <span v-else>{{
            item.format
              ? item.format(record[item.prop], record)
              : record[item.prop]
          }}</span>
        </template>
      </template>
    </a-table-column>
    <slot></slot>
    <a-table-column
      v-if="props.operate"
      fixed="right"
      :width="
        20 +
        (operateLabels.length + (props.extraBtns ?? 0)) *
          (size == 'small' ? 70 : 90)
      "
      :title="'操作'"
      align="center"
    >
      <template #default="{ record }">
        <div class="flex-x-around">
          <slot name="operate" :record="record"></slot>

          <ProButton
            :size="size"
            text="编辑"
            icon="formOutlined"
            type="primary"
            v-if="operateLabels.includes('编辑')"
            @click="props.operate['编辑']!(record)"
          />

          <ProButton
            :size="size"
            text="详情"
            icon="infoCircleOutlined"
            type="primary"
            v-if="operateLabels.includes('详情')"
            @click="props.operate['详情']!(record)"
          />

          <ProButton
            :size="size"
            text="删除"
            icon="deleteOutlined"
            type="primary"
            danger
            v-if="operateLabels.includes('删除')"
            @click="handleDelete(record)"
          />
        </div>
      </template>
    </a-table-column>
  </a-table>
</template>

<style lang="less" scoped>
.ant-table {
  .ant-table-thead > tr > th {
    background: blue;
  }
}
</style>
